#!/usr/bin/env bash

source ./config/env.sh
clear

mkdir -p ${K8S_DATA}/config/haproxy

cat > ${K8S_DATA}/config/haproxy/haproxy.cfg <<EOF
global
    log /dev/log    local0
    log /dev/log    local1 notice
    chroot /var/lib/haproxy
    stats socket /var/run/haproxy.sock mode 660 level admin
    stats timeout 30s
    user haproxy
    group haproxy
    daemon
    nbproc 1
defaults
    log     global
    timeout connect 5000
    timeout client  10m
    timeout server  10m
listen  admin_stats
    bind 0.0.0.0:${HAPROXY_STATUS_PORT}
    mode http
    log 127.0.0.1 local0 err
    stats refresh 30s
    stats uri /status
    stats realm welcome login\ Haproxy
    stats auth ${HAPROXY_NAME}:${HAPROXY_PASS}
    stats hide-version
    stats admin if TRUE
listen kube-master
    bind 0.0.0.0:${APISERVER_VIP_PORT}
    mode tcp
    option tcplog
    balance source
EOF


for master_ip in ${MASTER_IP}
do
  echo "=========================================== ${master_ip} ==========================================="
  sed -i '$a\    server '${master_ip}' '${master_ip}':6443 check inter 2000 fall 2 rise 2 weight 1' ${K8S_DATA}/config/haproxy/haproxy.cfg
done

for master_ip in ${MASTER_IP}
do
  echo "=========================================== ${master_ip} ==========================================="
  ssh root@${master_ip} "yum install -y haproxy"
  ssh root@${master_ip} "test -e ${HAPROXY_BIN_DIR} || mkdir -p ${HAPROXY_BIN_DIR}"
  scp ${K8S_DATA}/config/haproxy/haproxy.cfg root@${master_ip}:${HAPROXY_BIN_DIR}
  ssh root@${master_ip} "systemctl daemon-reload;systemctl enable haproxy;systemctl start haproxy"
  ssh root@${master_ip} "systemctl restart haproxy"
done

# 查看状态
for master_ip in ${MASTER_IP}
do
  echo "=========================================== ${master_ip} ==========================================="
  ssh root@${master_ip} "sudo systemctl status haproxy | grep Active"
done